<?php

/**
 *
 * @Front Controller class
 *
 * @package Core
 *
 */

class FrontController
{

	protected $_module, $_controller, $_action, $_registry;
	protected $pre_request = array();	

	public static $_instance;

	public static function getInstance()
	{
		if( ! (self::$_instance instanceof self) )
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	private function __construct()
	{
		
	}
	
	public function addPreRequest($pre_request) 
	{
		$this->pre_request[] = $pre_request;
	}
	
	public function dispatch()
	{
// 		$request = new Request($_SERVER['QUERY_STRING']);
		$request = new Request($this->getUri());		
		
		$this->_registry->oRequest = $request;
		
		$this->_module = $request->getModule(); 
		$this->_controller = $request->getController(); 
		$this->_action = $request->getAction(); 
		
		foreach ($this->pre_request as $pre_request) 
		{
			$result = Module::run($pre_request);
					
			if ($result) 
			{
				$request = $result;
				break;
			}
		}
			
		while ($request) {
			$request = Module::run($request);
		}
	}
	
	public function getModule()
	{
		return $this->_module;
	}

	public function getController()
	{
		return $this->_controller;
	}

	public function getAction()
	{
		return $this->_action;
	}

	public function getRegistry()
	{
		return $this->_registry;
	}

	public function setRegistry($registry)
	{
		$this->_registry = $registry;
	}
	
	private function getUri($prefix_slash = true)
	{
		if (isset($_SERVER['PATH_INFO']))
		{
			$uri = $_SERVER['PATH_INFO'];
		}
		elseif (isset($_SERVER['REQUEST_URI']))
		{
			$uri = $_SERVER['REQUEST_URI'];
			if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
			{
				$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
			}
			elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
			{
				$uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
			}
	
			// This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
			// URI is found, and also fixes the QUERY_STRING server var and $_GET array.
			if (strncmp($uri, '?/', 2) === 0)
			{
				$uri = substr($uri, 2);
			}
			$parts = preg_split('#\?#i', $uri, 2);
			$uri = $parts[0];
			if (isset($parts[1]))
			{
				$_SERVER['QUERY_STRING'] = $parts[1];
				parse_str($_SERVER['QUERY_STRING'], $_GET);
			}
			else
			{
				$_SERVER['QUERY_STRING'] = '';
				$_GET = array();
			}
			$uri = parse_url($uri, PHP_URL_PATH);
		}
		else
		{
			// Couldn't determine the URI, so just return false
			return false;
		}
	
		// Do some final cleaning of the URI and return it
		return ($prefix_slash ? '/' : '').str_replace(array('//', '../'), '/', trim($uri, '/'));
	}
	
	
} // end of class
